package de.playmee.views;

import java.util.List;

import de.playmee.ImageManager;
import de.playmee.Playmee;
import de.playmee.R;
import de.playmee.Track;
import de.playmee.handler.MusicHandler;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class SimpleLibraryViewAdapter extends BaseAdapter {
	
	private MusicHandler mHandler;
	private List<Track> tracks;
	private LayoutInflater inflater;
	private ImageManager imageManager;
	
	public SimpleLibraryViewAdapter(Activity activity, MusicHandler mHandler,
			List<Track> tracks) {
		this.mHandler = mHandler;
		this.tracks = tracks;
		inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		imageManager = ((Playmee) activity.getApplication()).getImageManager();
	}

	@Override
	public int getCount() {
		return tracks.size();
	}

	@Override
	public Object getItem(int position) {
		return null; // not needed
	}

	@Override
	public long getItemId(int position) {
		return tracks.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		ViewHolder holder;
		if (view == null) {
			view = inflater.inflate(R.layout.library_simpleitem, null);
			holder = new ViewHolder();
			holder.albumArt = (ImageView) view.findViewById(R.id.library_simpleitem_art);
			holder.artist = (TextView) view.findViewById(R.id.library_simpleitem_artist);
			holder.title = (TextView) view.findViewById(R.id.library_simpleitem_title);
			holder.duration = (TextView) view.findViewById(R.id.library_simpleitem_duration);
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		
		long trackId = getItemId(position);
		Track track = mHandler.loadTrack(trackId, false);
		
		holder.artist.setText(track.getArtist());
		holder.title.setText(track.getTitle());
		holder.duration.setText(formatDuration(track.getDuration()));
		synchronized(imageManager) {
			imageManager.displayImage(track, holder.albumArt);
		}

		return view;
	}
	
	private String formatDuration(long duration) {
		String dur = "";
		int min = (int) (duration / 1000 / 60);
		dur += (min < 10) ? ("0" + min) : min;
		dur += ":";
		int sec = (int) ((duration / 1000) % 60);
		int msec = (int) (duration % 1000);
		if (msec >= 500)
			sec++;
		dur += (sec < 10) ? ("0" + sec) : sec;
		return dur;
	}
	
	private static class ViewHolder {
		public ImageView albumArt;
		public TextView artist;
		public TextView title;
		public TextView duration;
	}
}
